/*
 * @Author: 杨有财
 * @Date: 2025-02-27 08:37:09
 * @LastEditTime: 2025-03-03 10:54:20
 * @LastEditors: 杨有财
 * @Description: 路由入口文件
 *
 */

import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';

import type { MenuRoute } from '@/types/interface';

import { registerNavigationGuard } from './guard';

/**
 * 注意：由于菜单暂时前端写死的，后期可能会换成后端返回，所以需要动态导入
 * 导入相关动态路由
 */
const homepageModules = import.meta.glob('./modules/**/*.ts', { eager: true });

// 存放动态路由
export const asyncRouterList: Array<RouteRecordRaw> = mapModuleRouterList(homepageModules);

// 存放固定路由
const defaultRouterList: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/login',
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/pages/login/page-login.vue'),
  },
  {
    path: '/404',
    name: 'Result404',
    component: () => import('@/pages/result/404/index.vue'),
    meta: { title: { zh_CN: '访问页面不存在页', en_US: 'Not Found', hidden: true } },
  },
];

// 将路由模块转换为路由
export function mapModuleRouterList(modules: Record<string, unknown>): Array<RouteRecordRaw> {
  const routerList: Array<RouteRecordRaw> = [];
  Object.keys(modules).forEach((key) => {
    // @ts-ignore
    const mod = modules[key].default || {};
    const modList = Array.isArray(mod) ? [...mod] : [mod];
    routerList.push(...modList);
  });
  return routerList;
}

export const getActive = (maxLevel = 3): string => {
  // 非组件内调用必须通过Router实例获取当前路由
  const route = router.currentRoute.value;
  if (!route.path) {
    return '';
  }

  return route.path
    .split('/')
    .filter((_item: string, index: number) => index <= maxLevel && index > 0)
    .map((item: string) => `/${item}`)
    .join('');
};

export const getFirstFullPath = (obj: MenuRoute | any) => {
  // 获取当前路由列表中第一个路由全路径
  if (obj) {
    if (!Object.prototype.hasOwnProperty.call(obj, 'children') || obj.children.length === 0) {
      return obj.path || '';
    }
    const child = obj.children[0];
    const childPath: string = getFirstFullPath(child);
    return `${obj.path || ''}/${childPath}`;
  }
  return '';
};

const router = createRouter({
  history: createWebHashHistory(),
  routes: defaultRouterList,
  scrollBehavior() {
    return {
      el: '#app',
      top: 0,
      behavior: 'smooth',
    };
  },
});

registerNavigationGuard(router);

export default router;
